<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;


class Order extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected $needUserLogin = ['getOrder', 'getDetail', 'cancelOrder'];


    /**
     * 获取订单列表
     * @throws \think\exception\DbException
     */
    public function getOrder()
    {
        if ($this->request->isPost()) {

            //类别:-1全部，0待支付，1待服务。2待评价，3退款
            //订单状态:0=待支付,1=待服务,2=待评价,3=已完成,4=退款中,5=已退款
            $type = trim($this->request->post('type'));
            $page = trim($this->request->post('page'));

            $data = (array)$this->_data;
            if ($type == -1) {//类别:-1全部，
                $orderList = Db::table('fa_order')
                    ->field(['id', 'service_name', 'area', 'main_image', 'cost_price', 'pay_price', 'appointmenttime', 'status', 'createtime', 'unit_price'])
                    ->where('user_id', $data['user_id'])
                    ->order('createtime desc')
                    ->paginate(5, null, ['page', $page]);
            } elseif ($type == 0 || $type == 1 || $type == 2) {//类别:，0待支付，1待服务。2待评价，
                $orderList = Db::table('fa_order')
                    ->field(['id', 'service_name', 'area', 'main_image', 'cost_price', 'pay_price', 'appointmenttime', 'status', 'createtime', 'unit_price'])
                    ->where('user_id', $data['user_id'])
                    ->where('status', $type)
                    ->order('createtime desc')
                    ->paginate(5, null, ['page', $page]);
            } else {//类别:退款
                $orderList = Db::table('fa_order')
                    ->field(['id', 'service_name', 'area', 'main_image', 'cost_price', 'pay_price', 'appointmenttime', 'status', 'createtime', 'unit_price'])
                    ->where('user_id', $data['user_id'])
                    ->whereIn('status', '4,5')
                    ->order('createtime desc')
                    ->paginate(5, null, ['page', $page]);

            }

            if (!$orderList) {

                $this->success('未查询到订单', [], 201);

            }

            $this->success('ok', ['orderList' => $orderList->items(), 'total' => $orderList->total()], 200);
        }
    }

    /**
     * 获取订单详情
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\db\exception\DataNotFoundException
     */
    public function getDetail()
    {
        if ($this->request->isPost()) {
            $id = trim($this->request->post('id'));

            $data = (array)$this->_data;

            if (!$id) {
                $this->success('缺少必要参数', [], 201);
            }

            $order = Db::table('fa_order')
                ->alias('a')
                ->field('a.*,c.province,c.city,c.districts,c.village')
                ->join('fa_village c', 'c.id=a.village_id')
                ->where('a.id', $id)
                ->where('user_id', $data['user_id'])
                ->find();

            if (!$order) {

                $this->success('未查询到订单', [], 201);

            }

            $order['fee'] = 0.00;
            $order['title'] = '未使用优惠券';

            if ($order['user_coupon_id']) {
                $userCoupon = Db::table('fa_user_coupon')
                    ->field('coupon_id')
                    ->where('id', $order['user_coupon_id'])
                    ->find();
                $coupon = Db::table('fa_coupon')
                    ->field('fee,title')
                    ->where('id', $userCoupon['coupon_id'])
                    ->find();
                if ($coupon) {
                    $order['fee'] = $coupon['fee'];
                    $order['title'] = $coupon['title'];
                }

            }

            $workerIds = explode(",", $order['worker_id']);

            $workerList = [];

            foreach ($workerIds as $key => $workerId) {
                $workerList[$key] = Db::table('fa_worker')
                    ->field(['id', 'avatar', 'name', 'age', 'score', 'mobile', 'service_count'])
                    ->where('id', $workerId)
                    ->find();
            }

            $this->success('ok', ['order' => $order, 'workerList' => $workerList], 200);
        }
    }

    /**
     * 取消订单
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\Exception
     */
    public function cancelOrder()
    {
        if ($this->request->isPost()) {

            $id = trim($this->request->post('id'));

            $data = (array)$this->_data;

            if (!$id) {
                $this->success('缺少必要参数', [], 201);
            }

            $order = Db::table('fa_order')
                ->where('id', $id)
                ->where('user_id', $data['user_id'])
                ->find();

            if ($order['status'] == 0) {

                Db::table('fa_order')
                    ->where('id', $id)
                    ->where('user_id', $data['user_id'])
                    ->delete();

                $this->success('订单已取消', [], 200);

            } elseif ($order['status'] == 1) {

                if ($order['appointmenttime'] - time() < 0) {

                    $this->success('此订单已超过预约时间，无法取消', [], 201);

                }
                if ($order['appointmenttime'] - time() < 60 * 30) {

                    $this->success('此订单距预约时间小于30分钟，无法取消', [], 201);

                }

                Db::table('fa_order')
                    ->where('id', $id)
                    ->where('user_id', $data['user_id'])
                    ->update([
                        'status' => 4,
                        'refund_reason' => '用户主动取消订单'
                    ]);

                $this->success('ok', [], 200);

            } else {

                $this->success('当前状态无法取消订单', [], 201);

            }
        }
    }
}